package mq;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

/**
 * @author Chenwx
 * @date 2021/5/13 15:28
 */
public class Consumer {
    public static void main(String[] args) throws MQClientException {
        //创建消费者
        DefaultMQPushConsumer c = new DefaultMQPushConsumer("consumer-group-1");
        //设置name service
        c.setNamesrvAddr("192.168.64.141:9876");
        //从 Topic1 订阅 TagA，TagB 等标签消息
        c.subscribe("Topic1", "TagA");
        //设置处理消息的监听器
        //Concurrently监听器可以启动多个线程 并执行多条消息
        c.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                for (MessageExt ext:list
                     ) {
                    byte[] body=ext.getBody();
                    String s=new String(body);
                    System.out.println("收到:"+s);
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        //启动
        c.start();
    }
}
